//阻塞队列

import java.sql.SQLOutput;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * Author: WJW
 * Date: 2024-08-09
 * Time: 19:50
 */

//队列空了，再出队列，同样也需要阻塞，同样是再另一个队列成功之后的线程中唤醒
class MyBlockingQueue{
    private Object locker = new Object();
    private String[] elems = null;
    private int head = 0;
    private int tail = 0;
    private int size = 0;

    public MyBlockingQueue(int capacity){
        elems = new String[capacity];
    }

    public void put(String elem) throws InterruptedException {
        synchronized (locker){
            while(size >= elems.length){
                //队列满了 后续需要让这个代码能够阻塞
                //使用wait来进行阻塞
                //把wait加入到if中，正好这个if在synchronized内部
                locker.wait();
            }
            //新的元素需要放到tail指向的位置上
            elems[tail] = elem;
            tail++;
            if(tail >= elems.length){
                tail = 0;
            }
            size++;

            //入队列成功之后进行唤醒
            locker.notify();
        }
    }

    public String take() throws InterruptedException {
        String elem = null;
        synchronized (locker){
            while (size == 0){
                //队列空了  后续也需要让这个代码阻塞
                locker.wait();

            }
            //取出head位置的元素并返回
            elem = elems[head];
            head++;
            if(head >= elems.length){
                head = 0;
            }
            size--;

            //元素出队列成功之和，加上唤醒
            locker.notify();
        }
        return elem;
    }
}
public class ThreadDemo {
    public static void main(String[] args) throws InterruptedException {
        MyBlockingQueue queue = new MyBlockingQueue(100);
      /*
        queue.put("aaa");
        queue.put("bbb");
        queue.put("ccc");
        queue.put("ddd");

        String elem = "";
        elem = queue.take();
        System.out.println("elem: " + elem);
        elem = queue.take();
        System.out.println("elem: " + elem);
        elem = queue.take();
        System.out.println("elem: " + elem);
        elem = queue.take();
        System.out.println("elem: " + elem);
    */


        //生产者
        Thread t1 = new Thread(()->{
            int n = 1;
            while(true){
                try {
                    queue.put(n+"");
                    System.out.println("生产元素 "+n);
                    n++;
                    //Thread.sleep(500);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });

        //消费者
        Thread t2 = new Thread(()->{
            while (true){
                try {
                    String n = queue.take();
                    System.out.println("消费元素 "+n);
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        t1.start();
        t2.start();
    }
}
